package com.android.miniskirt.ui;

import java.util.ArrayList;
import java.util.HashMap;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.miniskirt.R;
import com.android.miniskirt.miniApplication;
import com.android.miniskirt.ui.bubble9;

public class miniskirt extends ListActivity implements OnScrollListener{
	   private static final int GALLERY = 0;
	   private static final int MANU01 = 0;
	   private static final int MANU02 = 1;
	   private static final int MANU03 = 2;
	   private static final int MANU04 = 3;
	   private ArrayList<HashMap<String, Object>> mData;
	   private ArrayList<HashMap<String, Object>> mPinYin;
	   private ArrayList<HashMap<String, Object>> mValue = new ArrayList<HashMap<String, Object>>();
	   private miniApplication mApplication;
	   private HashMap<String, Object> mSuggestion;
	   private EditText editText;
	   private boolean flag = false;
	   MyAdapter adapter;
	   
	   private LinearLayout mLoadLayout;
	   private ListView mListView;
	   private int mLastItem = 0;
	   private int mCount = 0;
	   private final Handler mHandler = new Handler();
	   private final LayoutParams mProgressBarLayoutParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
	   private final LayoutParams mTipContentLayoutParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		
	   @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	    	super.onCreateOptionsMenu(menu);
	    	menu.add(GALLERY, MANU01, Menu.NONE, "添加好友")
	    	.setShortcut('0', 'k').setIcon(R.drawable.icon);
	    	menu.add(GALLERY, MANU02, Menu.NONE, "设置")
	    	.setShortcut('1', 's').setIcon(R.drawable.icon);
	    	menu.add(GALLERY, MANU03, Menu.NONE, "2-秋")
	    	.setShortcut('2', 'u').setIcon(R.drawable.icon);
	    	menu.add(GALLERY, MANU04, Menu.NONE, "3-冬")
	    	.setShortcut('3', 'n').setIcon(R.drawable.icon);
	    	return true;
	    }
	   @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	    	switch (item.getGroupId()) {
	    	case GALLERY:
	    		String itemid = Integer.toString(item.getItemId());
	    		String title = item.getTitle().toString();
	    		showAlertDialog("项目ID = " + itemid + "\n" +
	    				"标题 = " + title);
	    		return true;
	    	}
	    	return super.onOptionsItemSelected(item);
	    }
	    private void showAlertDialog(String message) {
	    	DisplayToast(message);
	    }
		@Override
 	    public void onCreate(Bundle savedInstanceState) {
 	        super.onCreate(savedInstanceState);
 	        setContentView(R.layout.tab1); 			
 	        mApplication = (miniApplication) this.getApplication();
 	        mData = mApplication.getContactsData();
 	        mPinYin = mApplication.getCn2enData();
 	        this.mCount = this.mData.size();
 	        this.adapter = new MyAdapter(this,mData);
 			/**
 			 * "加载项"布局，此布局被添加到ListView的Footer中。
 			 */
 			mLoadLayout = new LinearLayout(this);
 			mLoadLayout.setMinimumHeight(60);
 			mLoadLayout.setGravity(Gravity.CENTER);
 			mLoadLayout.setOrientation(LinearLayout.HORIZONTAL);
 			/**
 			 * 向"加载项"布局中添加一个圆型进度条。
 			 */
 			ProgressBar mProgressBar = new ProgressBar(this);
 			mProgressBar.setPadding(0, 0, 15, 0);
 			mLoadLayout.addView(mProgressBar, mProgressBarLayoutParams);
 			/**
 			 * 向"加载项"布局中添加提示信息。
 			 */
 			TextView mTipContent = new TextView(this);
 			mTipContent.setText("加载中...");
 			mLoadLayout.addView(mTipContent, mTipContentLayoutParams);
 			/**
 			 * 获取ListView组件，并将"加载项"布局添加到ListView组件的Footer中。
 			 */
 			mListView = getListView();
 			mListView.addFooterView(mLoadLayout);
 			/**
 			 * 组ListView组件设置Adapter,并设置滑动监听事件。
 			 */
 			setListAdapter(this.adapter);
 			mListView.setOnScrollListener(this);
 			
 	        editText = (EditText)findViewById(R.id.EditText01);
 	        String searchText = mData.size() + "个联系人";
 	        editText.setHint(searchText);
 	        editText.addTextChangedListener(new TextWatcher()
 	        {

				@Override
				public void afterTextChanged(Editable arg0) {
					// TODO Auto-generated method stub
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					// TODO Auto-generated method stub
					mValue.clear();
					String text = editText.getText().toString();
					String pinYin = null;
					if (text.length() == 0)
					{
						setListAdapter(miniskirt.this.adapter);
						return;
					}
					byte[] bytes = text.getBytes();
					int b = bytes.length;
					int j = text.length();
					if (b != j) {
						//输入搜索关键字为中文
						miniskirt.this.flag = true;
					}else {
						//输入搜索关键字为英文
						miniskirt.this.flag = false;
					}
					for(int i = 0; i < mPinYin.size(); i++)
					{
						mSuggestion = mPinYin.get(i);
						if (miniskirt.this.flag) {
							pinYin = mSuggestion.get("ItemTitle").toString();
						}else {
							pinYin = mSuggestion.get("PinYin").toString();
						}
						boolean flag = pinYin.contains(text);
						if (flag) {
							mValue.add(mSuggestion);
						}
					}
					final SuggestionAdapter adapterSuggestion = new SuggestionAdapter(miniskirt.this,mValue);
					setListAdapter(adapterSuggestion);
				}
 	        	
 	        });
 	    }//OnCreate
	
		public void DisplayToast(String str)
		{
			Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
		}
		@Override
		protected void onListItemClick(ListView l, View v, int position, long id) {

			startActivity(new Intent(miniskirt.this, bubble9.class));
		}
		
		public void showInfo(){

			new AlertDialog.Builder(this)

			.setTitle("选择照片")

			.setItems(R.array.items_irdc_dialog,new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if(which == 0)
					{
						DisplayToast("相册");
					}else if (which ==1)
					{
						DisplayToast("拍照");
					}else
					{
						DisplayToast("个人信息");
					}
				}
			})
			.show();
		}
		public final class ViewHolder{
 	        public ImageView img;
 	        public TextView title;
 	        public TextView info;
 	        public Button viewBtn;
 	    }
 	     
 	    public class MyAdapter extends BaseAdapter{
	 
 	        private LayoutInflater mInflater;
 	        private ArrayList<HashMap<String, Object>> mData = null; 
 	        int count = 20;
 	        public MyAdapter(Context context, ArrayList<HashMap<String, Object>> arrays){
 	            this.mInflater = LayoutInflater.from(context);
 	            this.mData = arrays;
 	        }
 	        
 	        @Override
	        public int getCount() {
 	            // TODO Auto-generated method stub
 	            return count;
 	        }
 	 
 	        @Override
 	        public Object getItem(int arg0) {
 	            // TODO Auto-generated method stub
 	            return arg0;
 	        }
	 
 	        @Override
 	        public long getItemId(int arg0) {
	            // TODO Auto-generated method stub
	            return arg0;
 	        }
 	 
 	        @Override
	        public View getView(int position, View convertView, ViewGroup parent) {
	             
 	            ViewHolder holder = null;
 	            if (convertView == null) {
 	                 
 	                holder=new ViewHolder(); 
 	                
	                convertView = mInflater.inflate(R.layout.vlist2, null);
 	                holder.img = (ImageView)convertView.findViewById(R.id.img);
 	                holder.title = (TextView)convertView.findViewById(R.id.title);
 	                holder.info = (TextView)convertView.findViewById(R.id.info);
	                convertView.setTag(holder);
	                 
	            }else {
 	                 
 	                holder = (ViewHolder)convertView.getTag();
 	            }
 	             	             
 	            holder.img.setBackgroundResource((Integer)mData.get(position).get("img"));
 	            holder.title.setText((String)mData.get(position).get("ItemTitle"));
 	            holder.info.setText((String)mData.get(position).get("ItemText"));
 	            holder.img.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
//						DisplayToast("imgimg");  
						showInfo();
					}
				});
 	           	return convertView;
        }//getView 	         
	 }//MyAdapter

 	    public class SuggestionAdapter extends BaseAdapter{
 	  	 
 	        private LayoutInflater mInflater;
 	        private ArrayList<HashMap<String, Object>> mData = null; 
 	        public SuggestionAdapter(Context context, ArrayList<HashMap<String, Object>> arrays){
 	            this.mInflater = LayoutInflater.from(context);
 	            this.mData = arrays;
 	        }
 	        
 	        @Override
	        public int getCount() {
 	            // TODO Auto-generated method stub
 	            return mData.size();
 	        }
 	 
 	        @Override
 	        public Object getItem(int arg0) {
 	            // TODO Auto-generated method stub
 	            return null;
 	        }
	 
 	        @Override
 	        public long getItemId(int arg0) {
	            // TODO Auto-generated method stub
	            return 0;
 	        }
 	 
 	        @Override
	        public View getView(int position, View convertView, ViewGroup parent) {
	             
 	            ViewHolder holder = null;
 	            if (convertView == null) {
 	                 
 	                holder=new ViewHolder(); 
 	                
	                convertView = mInflater.inflate(R.layout.vlist2, null);
 	                holder.img = (ImageView)convertView.findViewById(R.id.img);
 	                holder.title = (TextView)convertView.findViewById(R.id.title);
 	                holder.info = (TextView)convertView.findViewById(R.id.info);
	                convertView.setTag(holder);
	                 
	            }else {
 	                 
 	                holder = (ViewHolder)convertView.getTag();
 	            }
 	             	             
 	            holder.img.setBackgroundResource((Integer)mData.get(position).get("img"));
 	            holder.title.setText((String)mData.get(position).get("ItemTitle"));
 	            holder.info.setText((String)mData.get(position).get("ItemText"));
 	            holder.img.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
//						DisplayToast("imgimg");  
						showInfo();
					}
				});
 	           	return convertView;
        }//getView
	 }//SuggestionAdapter
 	    
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			mLastItem = firstVisibleItem + visibleItemCount - 1;
			if (this.adapter.count > mCount) {
				mListView.removeFooterView(mLoadLayout);
			}
		}
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			/**
			 * 当ListView滑动到最后一条记录时这时，我们会看到已经被添加到ListView的"加载项"布局， 这时应该加载剩余数据。
			 */
			if (mLastItem == this.adapter.count
					&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
				if (this.adapter.count <= mCount) {
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							miniskirt.this.adapter.count += 10;
							miniskirt.this.adapter.notifyDataSetChanged();
							mListView.setSelection(mLastItem);
						}
					}, 1000);
				}
			}
		}
}//MiniSkirt

